<?php

namespace Frieza\Modules\Creators\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Creator\AdmMyRight;
use Doraemon\model\Creator\AdmMyRightCorner;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\service\Right\UserRight;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class MyRightCornerController extends Controller
{
    const SHOW_TYPE = [1 => '有效期内展示一次'];

    private function getNames()
    {
        $res = [];
        $all = AdmMyRight::select('*', ['status' => 1]);
        if (empty($all)) {
            return $all;
        }
        foreach ($all as $v) {
            $res[$v['id']] = UserRight::$levelRightMap[$v['right_code']]['name'];
        }
        return $res;
    }
    public function list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $search['right_id'] = $request->input('right_id');
        $search['start'] = $request->input('time')['start'];
        $search['end'] = $request->input('time')['end'];
        $where = $this->buildWhere($search);
        $total = AdmMyRightCorner::count($where);
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $rights = AdmMyRightCorner::selectByWhere($where);
        $rightNames = $this->getNames();
        if ($rights) {
            $list = array_column($rights, 'id');
            $userProfiles = AdmOperationModule::getPositionRulesById($list, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT_CORNER);
            foreach ($rights as $key => $right) {
                $rights[$key]['user_profile'] = $userProfiles[$right['id']];
                $rights[$key]['icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $right['icon'], ImgUrl::IMAGE_SIZE_OP_ORI);
                $rights[$key]['start_time'] = date('Y-m-d H:i:s', $right['start_time']);
                $rights[$key]['end_time'] = date('Y-m-d H:i:s', $right['end_time']);
                $rights[$key]['right_id'] = $rightNames[$right['right_id']];
            }
        }
        $gridModel = new pGridDataModel($rights, $total, ['perPage' => $pageSize]);

        $gridList = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $rightNames) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->filter(function (Filter $filter) use ($rightNames) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($rightNames) {
                    $filter->in('right_id', '权益')->select($rightNames);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->between('time', '时间范围')->datetime();

                });
                $filter->expand();
            });

            $grid->column('id', 'ID')->sort();
            $grid->column('right_id', '权益名称');
            $grid->column('icon', '角标')->image();
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('remarks', '备注');
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('admin_id', '操作者')->display(function ($operator) {
                return Admin::user()->find($operator)->name;
            });
            $grid->actions(function ($action) {
            });
        });
        $tab = new Tab();
        $tab->add('权益角标', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('权益角标')
            ->description(' ')
            ->breadcrumb(['text' => '权益角标']);
    }

    public function create(Content $content)
    {
        $rightNames = $this->getNames();
        $tab = new Tab();
        $form = new Form();
        $form->radio('time_type', '展示时间')
            ->options([1 => '指定时间段', 2 => '永久生效'])
            ->when(1, function (Form $form) {
                $form->datetime('start_time', '开始显示时间');
                $form->datetime('end_time', '显示结束时间');
            })->when(2, function (Form $form) {
                $form->datetime('start_time', '开始显示时间');
            })->required();
        $form->select('right_id', '权益')->options($rightNames)->required();
        $form->radio('show_type', '展示方式')->options(self::SHOW_TYPE)->required();
        $form->imgUpload('icon', '角标')->help('图标，必须需要上传');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->text('remarks', '备注');
        $form->action('/admin/creators/myrightcorner/save');
        $tab->add('添加权益', $form, true);
        $content->header('添加权益')
            ->breadcrumb(
                ['text' => '我的权益', 'url' => '/creators/myrightcorner/list'],
                ['text' => '添加我的权益',]
            )
            ->row($tab);
        return $content;
    }

    public function save(Request $request)
    {
        $params = $request->all();
        // 2121 年 int最大值
        $params['end_time'] = $params['end_time'] ?? '2038-01-01 00:00:00';
        $where = [
            'right_id' => $params['right_id'],
            'status' => AdmMyRight::STATUS_NORMAL,
            'OR' => [
                'AND #1' => [
                    'start_time[<]' => strtotime($params['start_time']),
                    'end_time[>]' => strtotime($params['start_time']),
                ],
                'AND #2' => [
                    'start_time[<]' => strtotime($params['end_time']),
                    'end_time[>]' => strtotime($params['end_time']),
                ],
                'AND #3' => [
                    'start_time[>]' => strtotime($params['start_time']),
                    'end_time[<]' => strtotime($params['end_time']),
                ],
            ]
        ];
        if (!empty(AdmMyRightCorner::getByWhere($where))) {
            $error = new MessageBag([
                'title' => '权益角标已经存在，时间交叉'
            ]);
        } else {
            $userProfile = $params['user_profile'];
            $data = [
                'status' => AdmMyRightCorner::STATUS_NORMAL,
                'addtime' => time(),
                'edittime' => time(),
                'admin_id' => Admin::user()->id,
                'right_id' => $params['right_id'],
                'icon' => $params['icon'] ?? '',
                'start_time' => strtotime($params['start_time']),
                'end_time' => strtotime($params['end_time']),
                'time_type' => $params['time_type'],
                'show_type' => $params['show_type'],
                'remarks' => $params['remarks'],
            ];
            $id = AdmMyRightCorner::addRightsCorner($data);
            //用户分群
            if ($id) {
                AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT_CORNER);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            if ($id) {
                return redirect('/admin/creators/myrightcorner/list')->with(compact('success'));
            }
        }
        return redirect('/admin/creators/myrightcorner/list')->with(compact('error'));
    }

    public function edit(Content $content, $id)
    {
        $rightNames = $this->getNames();
        $tab = new Tab();
        $where = ['id' => $id];
        $list = AdmMyRightCorner::get('*', $where);
        $data = [
            'time_type' => $list['time_type'],
            'start_time' => date('Y-m-d H:i:s', $list['start_time']),
            'end_time' => date('Y-m-d H:i:s', $list['end_time']),
            'right_id' => $list['right_id'],
            'show_type' => $list['show_type'],
            'remarks' => $list['remarks'],
            'icon' => $list['icon'],
            "user_profile" => AdmOperationModule::getPositionRulesById($id, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT_CORNER, true)
        ];
        $form = new Form($data);
        $form->radio('time_type', '展示时间')
            ->options([1 => '指定时间段', 2 => '永久生效'])
            ->when(1, function (Form $form) {
                $form->datetime('start_time', '开始显示时间');
                $form->datetime('end_time', '显示结束时间');
            })->when(2, function (Form $form) {
                $form->datetime('start_time', '开始显示时间');
            });
        $form->select('right_id', '权益')->options($rightNames)->required();
        $form->radio('show_type', '展示方式')->options(self::SHOW_TYPE);
        $form->imgUpload('icon', '角标')->help('图标，必须需要上传');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->text('remarks', '备注');
        $tab->add('修改权益角标', $form, true);
        $form->action('/admin/creators/myrightcorner/' . $id . '/update');
        $content->header('我的权益角标')
            ->breadcrumb(
                ['text' => '我的权益角标', 'url' => '/creators/myrightcorner/list'],
                ['text' => '修改权益角标',]
            )
            ->row($tab);
        return $content;
    }

    public function editSave(Request $request, $id)
    {
        $params = $request->input();
        // 2121 年 int最大值
        $params['end_time'] = $params['end_time'] ?? '2038-01-01 00:00:00';
        $where = [
            'id[!]' => $id,
            'right_id' => $params['right_id'],
            'status' => AdmMyRight::STATUS_NORMAL,
            'OR' => [
                'AND #1' => [
                    'start_time[<]' => strtotime($params['start_time']),
                    'end_time[>]' => strtotime($params['start_time']),
                ],
                'AND #2' => [
                    'start_time[<]' => strtotime($params['end_time']),
                    'end_time[>]' => strtotime($params['end_time']),
                ],
                'AND #3' => [
                    'start_time[>]' => strtotime($params['start_time']),
                    'end_time[<]' => strtotime($params['end_time']),
                ],
            ]
        ];
        if (!empty(AdmMyRightCorner::getByWhere($where))) {
            $error = new MessageBag([
                'title' => '权益角标已经存在,时间交叉'
            ]);

        } else {
            $userProfile = $params['user_profile'];
            $data = [
                'status' => AdmMyRightCorner::STATUS_NORMAL,
                'edittime' => time(),
                'admin_id' => Admin::user()->id,
                'right_id' => $params['right_id'],
                'icon' => $params['icon'] ?? '',
                'start_time' => strtotime($params['start_time']),
                'end_time' => strtotime($params['end_time']),
                'time_type' => $params['time_type'],
                'show_type' => $params['show_type'],
                'remarks' => $params['remarks']
            ];
            if ($id) {
                $result = AdmMyRightCorner::updateById($data, $id);
                AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_MY_RIGHT_CORNER);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            if ($result) {
                return redirect('/admin/creators/myrightcorner/list')->with(compact('success'));
            }
        }

        return redirect('/admin/creators/myrightcorner/list')->with(compact('error'));
    }

    public function deleteById($id)
    {
        $result = AdmMyRightCorner::deleteById($id);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        $error = new MessageBag([
            'title' => '操作失败'
        ]);

        if ($result) {
            return redirect('/admin/creators/myrightcorner/list')->with(compact('success'));
        }
        return redirect('/admin/creators/myrightcorner/list')->with(compact('error'));
    }

    private function buildWhere($search = [])
    {
        $where = [];

        if ($search['right_id']) {
            $where['right_id'] = $search['right_id'];
        }
        if ($search['start']) {
            $where['start_time[>]'] = strtotime($search['start']);
        }
        if ($search['end']) {
            $where['end_time[<]'] = strtotime($search['end']);
        }
        $where['status'] = AdmMyRight::STATUS_NORMAL;
        $where['ORDER'] = ['corner_sort' => 'ASC', 'id' => 'DESC'];
        return $where;
    }

    public function sort(Request $request)
    {
        $sort = $request->input('sort');
        if (isset($sort)) {
            AdmMyRightCorner::weight($sort);
        }
    }

}